package com.juphoon.oauth.browser;

import com.juphoon.oauth.browser.filter.ImageCodeFilter;
import com.juphoon.oauth.browser.handler.AuthFailHandler;
import com.juphoon.oauth.browser.handler.AuthSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author cynic
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthSuccessHandler authSuccessHandler;

    @Autowired
    private AuthFailHandler authFailHandler;




    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ImageCodeFilter imageCodeFilter = new ImageCodeFilter(authFailHandler);
        http.addFilterBefore(imageCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .loginPage("/loginPage")
                .loginProcessingUrl("/auth")
                .successHandler(authSuccessHandler)
                .failureHandler(authFailHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/loginPage", "/imageCode", "/jquery.min.js").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .authorizeRequests()
                .anyRequest().access("@rbacPermission.hasPermission(request, authentication)")
                .and().csrf().disable();
    }
}
